package com.cory.admin.sys.service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Lists;
import com.cory.admin.sys.domain.entity.SysRoleResource;
import com.cory.admin.sys.mapper.SysRoleResourceMapper;

/**
 *  服务实现类
 *
 * @author xc
 * @since 2019-02-23
 */
@Service
public class SysRoleResourceService extends ServiceImpl<SysRoleResourceMapper, SysRoleResource> {
    @Autowired
    private SysResourceService sysResourceService;
    
    public List<Integer> selectRoleResourceIds(Integer roleId) {
        return baseMapper.selectRoleResourceIds(roleId);
    }
    
    @Transactional(rollbackFor=Exception.class)
    public void saveRoleResources(Integer roleId, List<Integer> resourceIds) {
        List<Integer> roleResourceIds = this.selectRoleResourceIds(roleId);
        
        // 补全一级和二级分类
        Set<Integer> resourceIds_2 = sysResourceService.selectResourcePIds(resourceIds);
        Set<Integer> resourceIds_1 = sysResourceService.selectResourcePIds(resourceIds_2);
        resourceIds.addAll(0, resourceIds_2);
        resourceIds.addAll(0, resourceIds_1);
        
        List<Integer> addResourceIds = resourceIds.stream().filter(i -> !roleResourceIds.contains(i)).collect(Collectors.toList());
        List<Integer> delResourceIds = roleResourceIds.stream().filter(i -> !resourceIds.contains(i)).collect(Collectors.toList());
        
        List<SysRoleResource> addResources = Lists.newArrayList();
        for (Integer resourceId : addResourceIds) {
            SysRoleResource resource = new SysRoleResource();
            resource.setResourceId(resourceId);
            resource.setRoleId(roleId);
            
            addResources.add(resource);
        }
        if (addResources.size() > 0) {
            super.saveBatch(addResources);
        }
        
        if (delResourceIds.size() > 0) {
            UpdateWrapper<SysRoleResource> wrapper = new UpdateWrapper<>();
            wrapper.eq("role_id", roleId).in("resource_id", delResourceIds);
            super.remove(wrapper);
        }
    }
    
}
